/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shared;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author eric
 */
public class FileUploadManager extends FileTransferManager implements Runnable {

    private static final boolean DEBUG=false;
    private InputStream inputStream;
    private OutputStream outputStream;
    private int offset;
    private int bytesSent;


    public FileUploadManager(FileInfo info, InputStream input, OutputStream output, int offset )
    {
        super();
        bytesSent = 0;
        setStatus (TransferStatus.IN_PROGRESS);
        this.fileInfo = info;
        this.outputStream = output;
        this.inputStream = input;
        this.offset = offset;
        if(info.getFileSize() < MAX_CHUNK_SIZE)
            chunkSize = info.getFileSize().intValue();
        else
            chunkSize = MAX_CHUNK_SIZE;
    }

    public void run() {
        byte[] buffer = new byte[chunkSize];
        try {
            int bytesRead = 0;
            if (offset!=0)
                    inputStream.read(new byte[offset],0, offset);
            
            bytesRead = inputStream.read(buffer);
          
                
            while (bytesRead >  -1) {
                if (DEBUG)
                {
                    try {
                        sleep(800);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(FileUploadManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (bytesRead < chunkSize)
                {
                    outputStream.write(buffer, 0, bytesRead);

                }
                else
                {
                    outputStream.write(buffer);
                }
                outputStream.flush();
                bytesRead = inputStream.read(buffer);
            }
            setStatus(TransferStatus.COMPLETE);

            outputStream.close();
            
        } catch (IOException ex) {
           setStatus (TransferStatus.COMPLETE);
        }
    }


}
